# -*- coding: utf-8

import sys
import wx
import logging
import traceback
import StringIO
from optparse import OptionParser

from mainframe import MainFrame

def parse_option():
  # parse parameter and debug
  oparser = OptionParser()
  oparser.add_option( "-d",
      dest="debug", action="store_true", default=False,
      help="set debug level")
  oparser.add_option( "-f",
      dest="debug_file", action="store", type="string",
      help="set debug filename")
  (opt, arg) = oparser.parse_args()
  # if opt.debug:
  #  logging.root.setLevel(level=logging.DEBUG)

  return (opt.debug, opt.debug_file, arg)
 
def main():
  consolebuf = StringIO.StringIO()

  _stdout = sys.stdout
  _stderr = sys.stderr

  (debug, debug_file, arg)  = parse_option()

  try:
    sys.stdout = consolebuf
    sys.stderr = consolebuf
    if debug:
      logging.basicConfig(level=logging.DEBUG)
    else:
      logging.basicConfig(level=logging.ERROR)
    
    app = wx.PySimpleApp()
    my = MainFrame(None)
    if len(arg) >= 1:
      my.OpenFile( arg[0].decode( sys.getfilesystemencoding() or 'ascii' ) )
    my.Show()
    app.MainLoop()
  except:
    traceback.print_exc()
  
  try:
    if consolebuf.tell() > 0:
      fp = openLogFile( debug_file )
      fp.write( consolebuf.getvalue() )
      fp.close()
  except:
    print >>_stderr, consolebuf.getvalue()
    print >>_stderr, traceback.format_exc()

def openLogFile(debug_file):
  if debug_file is None:
    import os
    import os.path

    base_dir = ""

    if 'HOME' in os.environ:
      base_dir = os.environ['HOME']
    elif ( 'HOMEDRIVE' in os.environ ) and ( 'HOMEPATH' in os.environ ):
      base_dir = os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
    elif 'TEMP' in os.environ:
      base_dir = os.environ['TEMP']
    elif os.name == 'posix':
      base_dir = '/tmp'
    else:
      # no way to escape
      pass # remain empty

    debug_file = os.path.join( base_dir, "todo-xmind.log" )

  return open( debug_file, "w" )
main()

